enum StorageType {
  LocalStorage = 'localStorage',
  SessionStorage = 'sessionStorage',
}

interface StorageData {
  data: Record<string, any>;
}

const STORAGE_KEY = {
  AREA_LIST: 'AREA_LIST',
  CITY_LIST: 'CITY_LIST',
  REMEMBER_PASSWORD: 'REMEMBER_PASSWORD',
};

const useStorage = (
  scope: string,
  storageType: StorageType = StorageType.LocalStorage,
) => {
  // 根据传入的 storageType 选择使用 localStorage 或 sessionStorage
  const storage =
    storageType === StorageType.SessionStorage ? sessionStorage : localStorage;

  // 设置存储数据
  const set = (key: string, value: any): void => {
    try {
      storage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.error('Error setting item in storage:', error);
    }
  };

  // 获取存储数据，确保找不到时返回 null
  const get = <T>(key: string): T | null => {
    try {
      const value = storage.getItem(key);
      // 如果没有找到数据或解析失败，返回 null
      return value ? JSON.parse(value) : null;
    } catch (error) {
      console.error('Error getting item from storage:', error);
      return null;
    }
  };

  // 作用域前缀，用于确保每个存储项的唯一性
  const $scope = `__STORAGE__${scope}___`;

  return {
    // 设置某个键值对
    set: (key: string, value: any): void => {
      const store: StorageData = get($scope) || { data: {} };
      store.data[key] = value;
      set($scope, store);
    },

    // 获取某个键的值，找不到返回 null
    get: <T>(key: string): T | null => {
      const store: StorageData = get($scope) || { data: {} };
      return store.data[key] ?? null; // 如果没找到，返回 null
    },

    // 删除某个键
    remove: (key: string): void => {
      const store: StorageData = get($scope) || { data: {} };
      delete store.data[key];
      set($scope, store);
    },

    // 清除整个作用域的数据
    clear: (): void => {
      try {
        storage.removeItem($scope);
      } catch (error) {
        console.error('Error clearing storage:', error);
      }
    },
  };
};

export { useStorage, StorageType, STORAGE_KEY };
